package com.android.pindaojia.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.pindaojia.model.group.CitySetDataCallback;
import com.android.pindaojia.view.recycleview.LineGridView;
import com.android.pindaojia.R;
import com.android.pindaojia.app.BaseActivity;
import com.android.pindaojia.cache.search.RecordsDao;
import com.android.pindaojia.model.group.CityChooseData;
import com.android.pindaojia.model.group.CityChooseDataCallback;
import com.android.pindaojia.model.group.CitySetData;
import com.android.pindaojia.utils.ConstantsUrl;
import com.android.pindaojia.utils.HttpUtils;
import com.android.pindaojia.utils.LoginState;
import com.android.pindaojia.utils.MyLog;
import com.android.pindaojia.utils.ObjectUtils;
import com.android.pindaojia.view.MyListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/14.
 */

public class CityChoose extends BaseActivity {
    @BindView(R.id.search_layout)
    LinearLayout search_layout;
    @BindView(R.id.citychoose_scrollview)
    ScrollView citychoose_scrollview;
    @BindView(R.id.locate_city)
    TextView locate_city;
    @BindView(R.id.hot_city)
    LineGridView hot_city;
    @BindView(R.id.more_city)
    LineGridView more_city;
    @BindView(R.id.citychoose_listview)
    MyListView listView;
    @BindView(R.id.result_listview)
    MyListView resultlistView;
//    @BindView(R.id.click_resetnetwork)
//    LinearLayout clickResetnetwork;
//    @BindView(R.id.progress)
//    RelativeLayout progress;
//    @BindView(R.id.no_data)
//    RelativeLayout noData;
//    @BindView(R.id.no_data_tv)
//    TextView noDataTv;
//    @BindView(R.id.progress_loading)
//    FrameLayout progressLoading;
    private View view;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private CityChoose mcontext;
    private String local_city;
    private ArrayList<String> pin = new ArrayList<String>();
    private ArrayList<CityChooseData.DataBean.Hot_ListBean> hot_list =new ArrayList<>();
    private ArrayList<ArrayList<CityChooseData.DataBean.PinList>> pinlists= new ArrayList<>();
    private GridCityAdapt adapter_city1;
    private GridCityAdapt1 adapter_city2;
    private GridCityAdapt1 adapter_city3;
    private GridCityAdapt2 adapter;
    private RecordsDao recordsDao;
    private String zone;
    private String returncity;
    private String title;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_citychoose);
        ButterKnife.bind(this);
        initTitle(0,"选择城市");
        mcontext = CityChoose.this;
        recordsDao = new RecordsDao(mcontext);
        GetCityChoose();
    }
   private void initUI()
   {
       locate_city.setText(local_city);
       adapter_city1 = new GridCityAdapt(hot_list);
       hot_city.setAdapter(adapter_city1);
       adapter_city2 = new GridCityAdapt1(pin);
       more_city.setAdapter(adapter_city2);
       adapter  = new GridCityAdapt2(pinlists);
       listView.setAdapter(adapter);
       hot_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                     PostCityChoose(hot_list.get(i).getId());
           }
       });
       more_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
               int[] location = new int[2];
               more_city.getLocationOnScreen(location);
                     int y = location[1];
               int totalHeight =y;
               for(int j=0;j<i;j++) {
                   View listItem = adapter.getView(j, null, listView);    //获取到ListView中item对应的view
                   listItem.measure(0, 0);                                //获取到view的高度
                   totalHeight += listItem.getMeasuredHeight();
               }
               citychoose_scrollview.smoothScrollTo(0,totalHeight);

           }
       });


   }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case 0:
                 finish();
                break;

        }
    }
    @OnClick({R.id.search_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_layout:
                Intent intent_search = new Intent(mcontext, CitySearch.class);
                int requestcode=0;
                startActivityForResult(intent_search,requestcode);
                break;
        }
    }
    private void GetCityChoose()
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.CITYCHOOSE;
        MyLog.e("地址", address);
        if (networkConnected) {
            HttpUtils.get(address, null, new CityChooseDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    //ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(CityChooseData response, int id) {
                   // ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        pin.clear();
                        hot_list.clear();
                        pinlists.clear();
                        if (response.getData().getPin()!= null&&response.getData().getPin_list()!= null&&response.getData().getHot_list()!= null) {
                            local_city = response.getData().getLocal_city();
                            pin.addAll(response.getData().getPin());
                            hot_list.addAll(response.getData().getHot_list());
                            Map<String,ArrayList<CityChooseData.DataBean.PinList>> pin_list = response.getData().getPin_list();
                            for(String key:pin_list.keySet())
                            {
                                int length = pin_list.get(key).size();
                                pinlists.add(pin_list.get(key));
                                //判断数据库中是否存在该记录
                                for(int i=0;i<length;i++)
                                {
                                    if (!recordsDao.isHasMoreCity(pin_list.get(key).get(i).getName())) {

                                        //将搜索记录保存至数据库中
                                        recordsDao.addMorecity(pin_list.get(key).get(i).getId(),pin_list.get(key).get(i).getName(),pin_list.get(key).get(i).getPin());
                                    }
                                }
                            }
                            initUI();
                        }
                    } else {
//                        noData.setVisibility(View.VISIBLE);
//                        noDataTv.setText(response.getMsg());
//                        noDataTv.setVisibility(View.VISIBLE);
                    }

                }
            });
        } else {
           // ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "连接连接出现异常");
        }
    }
    private void PostCityChoose(String id)
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.CITYSET;
        String getid = LoginState.getInstance().getid(mcontext);
        String getpd = LoginState.getInstance().getpd(mcontext);
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("UPSW", getpd);
        map.put("id",id);
        if (networkConnected) {
            HttpUtils.post(address,header, map, new CitySetDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                   // ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(CitySetData response, int id) {
                  //  ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        zone = response.getData().getZone();
                        returncity = response.getData().getCity();
                        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString(ConstantsUrl.USERDATA_ZONE,zone);
                        edit.putString(ConstantsUrl.USERDATA_CITY,returncity);
                        edit.commit();
                        Intent intent = new Intent();
                        intent.setAction(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_LOCATION_CHANGE);
                        mcontext.sendBroadcast(intent);
                        finish();
                    } else {
                      //  noData.setVisibility(View.VISIBLE);
                       // noDataTv.setText(response.getMsg());
                      //  noDataTv.setVisibility(View.VISIBLE);
                    }

                }
            });
        } else {
          //  ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "连接连接出现异常");
        }
    }
    public class GridCityAdapt extends BaseAdapter {
        private ArrayList<CityChooseData.DataBean.Hot_ListBean> listdata;

        public GridCityAdapt( ArrayList<CityChooseData.DataBean.Hot_ListBean> listdata) {
            this.listdata = listdata;
        }
        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            holder = new ViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.citychoose_grid_detail, null);
                holder.textView = (TextView) convertView.findViewById(R.id.citychoose_griddetail_textview);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(listdata.get(position).getName());
            return convertView;
        }
         class ViewHolder {
            TextView textView;
        }
    }
    public class GridCityAdapt1 extends BaseAdapter {
        private ArrayList<String> listdata;

        public GridCityAdapt1(ArrayList<String>listdata) {
            this.listdata = listdata;
        }
        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            holder = new ViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.citychoose_grid_detail, null);
                holder.textView = (TextView) convertView.findViewById(R.id.citychoose_griddetail_textview);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(listdata.get(position));
            return convertView;
        }
        class ViewHolder {
            TextView textView;
        }
    }
    public class GridCityAdapt2 extends BaseAdapter {
        private ArrayList<ArrayList<CityChooseData.DataBean.PinList>> listdata;

        public GridCityAdapt2(ArrayList<ArrayList<CityChooseData.DataBean.PinList>> listdata) {
            this.listdata = listdata;
        }
        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            holder = new ViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.citychoose_listview, null);
                holder.gridView = (LineGridView) convertView.findViewById(R.id.citys);
                holder.textView = (TextView) convertView.findViewById(R.id.FirstSpell);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.textView.setText(listdata.get(position).get(0).getPin());
            ArrayList<String> citys=new ArrayList<>();
            for(int i=0;i<listdata.get(position).size();i++)
            {
                citys.add(listdata.get(position).get(i).getName());
            }
            adapter_city3 = new GridCityAdapt1(citys);
            holder.gridView.setAdapter(adapter_city3);
            holder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                    PostCityChoose(listdata.get(position).get(i).getId());
                }
            });
            return convertView;
        }
        class ViewHolder {
            TextView textView;
            LineGridView gridView;
        }
    }
}
